package com.letv.android.client;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import com.ledim.app.LeDimApplication;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.LedimChoiceCardBean;
import com.flurry.android.FlurryAgent;
import com.letv.ads.AdsManager;
import com.letv.android.client.utils.AlbumLaunchUtils;
import com.letv.android.client.webview.JSBridgeUtil;
import com.letv.business.flow.album.AlbumFlowUtils;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.component.player.core.LetvMediaPlayerManager;
import com.letv.component.player.utils.CpuInfosUtils;
import com.letv.component.player.utils.NativeInfos;
import com.letv.core.api.LetvHttpApiConfig;
import com.letv.core.bean.IVideo;
import com.letv.core.bean.TimestampBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.AutoSwitchHandler;
import com.letv.core.utils.LetvSDKUtils;
import com.letv.core.utils.LetvTools;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.PlayUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.LetvErrorCode;
import com.letv.pp.func.CdeHelper;
import com.letv.pp.listener.OnServiceConnectionListener;

//import com.letv.plugin.pluginloader.util.JarUtil;

/**
 */
public class LetvSDK {

    public static final String CDELOG1 =
            Environment.getExternalStorageDirectory() + "/letv/exceptionInfo/cde.txt";

    private LetvSDKCallback letvSDKCallback;

    protected CdeHelper mCdeHelper;

    private boolean isInited = false;

    // 默认走硬解m3u8
    protected boolean mDefaultHardStreamDecorder = false;
    /**
     * 视频类型
     **/
    public String mVideoFormat = "mp4";
    protected int mSupportLevel = 0;
    /**
     * 码流
     **/
    protected int mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
    /**
     * 广告相关
     */
    protected int pushType;

    private boolean mIsCdeStarting = true;

    private boolean mIsCdeReady = true;

    private IVideo mVideo;

    private LetvSDK() {
    }

    private static LetvSDK instance = new LetvSDK();

    public static LetvSDK getInstance() {
        return instance;
    }

    public void registerCallBack(LetvSDKCallback letvSDKCallback) {
        this.letvSDKCallback = letvSDKCallback;
    }

    public LetvSDKCallback getCallBack() {
        return letvSDKCallback;
    }

    /**
     * 调用乐视视频SDK播放在线视频
     *
     * @param context
     * @param video
     */
    public void play(Context context, IVideo video, boolean isLocal, LedimChoiceCardBean card) {
        this.mVideo = video;
        if (isLocal) {
            AlbumLaunchUtils.launch(context, 0, 0, PlayConstant.LAUNCH_FROM_UNKONW, card);
        } else {
            AlbumLaunchUtils.launch(context, 0, video.getmVid(), PlayConstant.LAUNCH_MODE_ALBUM, card);
        }
        StatisticsUtils.statisticsLogin(context, 0, "errortolite");
    }

    //搜索结果中的相关视频
    public void play(Context context, IVideo video, boolean isLocal, LedimChoiceCardBean card,
                     boolean isLoadData) {
        this.mVideo = video;
        if (isLocal) {
            AlbumLaunchUtils.launch(context, 0, 0, PlayConstant.LAUNCH_FROM_UNKONW, card, isLoadData);
        } else {
            AlbumLaunchUtils.launch(context, 0, video.getmVid(), PlayConstant.LAUNCH_MODE_ALBUM, card, isLoadData);
        }
        StatisticsUtils.statisticsLogin(context, 0, "errortolite");
    }

    /**
     * 调用乐视视频SDK播放放映厅
     *
     * @param context
     * @param video
     */
    public void playRoom(Context context, IVideo video, ChatRoomBean room) {
        this.mVideo = video;
        AlbumLaunchUtils.launchRoom(context, 0, video.getmVid(), PlayConstant.LAUNCH_MODE_ALBUM, room);
        StatisticsUtils.statisticsLogin(context, 0, "errortolite");
    }

    public void playRoom(Context context, IVideo video, ChatRoomBean room, boolean isMe,
                         boolean isFromEditScreenRoom) {
        this.mVideo = video;
        AlbumLaunchUtils.launchRoom(context, 0, video.getmVid(), PlayConstant.LAUNCH_MODE_ALBUM, room, isMe, isFromEditScreenRoom);
        StatisticsUtils.statisticsLogin(context, 0, "errortolite");
    }

    public void playRoom(Context context, IVideo video, ChatRoomBean room, boolean isMe,
                         boolean isFromEditScreenRoom, boolean fromPushMsg) {
        this.mVideo = video;
        AlbumLaunchUtils.launchRoom(context, 0, video.getmVid(), PlayConstant.LAUNCH_MODE_ALBUM, room, isMe, isFromEditScreenRoom, fromPushMsg);
        StatisticsUtils.statisticsLogin(context, 0, "errortolite");
    }
    /**
     * 调用乐视视频SDK获取下载地址
     *
     * @param context
     * @param video
     */
    public void parseRefVidByThirdParty(Context context, IVideo video) {
        if (null == video) {
            Log.e("sguotao", "Letv get download url failed,video is null!");
            return;
        }
        if (null == context) {
            Log.e("sguotao", "Letv get download url failed,context is null!");
            return;
        }

        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putLong(PlayConstant.VID, video.getmVid());
        intent.putExtras(bundle);
        AlbumPlayFlow mPlayAlbumFlow =
                AlbumFlowUtils.getPlayFlow(context, PlayConstant.LAUNCH_MODE_DOWNLOAD, intent.getExtras());
        mPlayAlbumFlow.start();
    }

    /**
     * 乐视视频回调Callback
     */
    public interface LetvSDKCallback {

        void onEvent(int event, String name, IVideo video);
    }

    /**
     * SDK 初始化操作
     */
    public void init() {
        if (isInited) {
            Log.e("LetvSDK", "Letv SDK is already inited!");
            return;
        }

        LetvSDKUtils.initScreenInfo(LeDimApplication.getInstance());

        // 设置统计环境,上报崩溃统计
        DataStatistics.getInstance().setDebug(LetvConfig.isDebug());
        staticsCrashInfo();

        // 初始化插件
        //        JarUtil.initJars(mContext);

        // 播放器初始化
        initLetvMediaPlayerManager();
        setVType();
        initAds();

        //初始化Flurry
        initFlurry();

        // utp 运营信息
        PreferencesManager.getInstance(LeDimApplication.getInstance()).setUtp(true);

        startCde();
        LetvHttpApiConfig.initialize(LetvConfig.getPcode(LeDimApplication.getInstance()
                                                                         .getApplicationContext()), LetvTools
                .getClientVersionName(LeDimApplication.getInstance().getApplicationContext()));

        isInited = true;
    }

    /**
     * 启动cde服务 获取CdeHelper实例： getInstance(Context context, String
     * params)---默认先升级； getInstance(Context context, String params, boolean
     * isFirstUpgrade) isFirstUpgrade为true标示先升级在启动，为false表示静默升级
     */
    public void startCde() {
        //if (null == mContext) {
        //    Log.e("LetvSDK", "start cde failed,context is null!");
        //    return;
        //}
        // app_id 表示当前 APP 的标识，保持和之前 UTP 的一致即可。
        //        String appId = "3000";
        //基线CDE的port为6994,乐次元为7002
        String appId = LetvConfig.getAppId();
        String params = "port=7002&app_id=" + appId +
                "&ostype=android&channel_default_multi=0&log_type=4&log_file=" + LetvSDK.CDELOG1 +
                "&channel_default_multi=1&channel_max_count=2&dcache_enabled=1&dcache_capacity=50";
        if (mCdeHelper == null) {
            mCdeHelper = CdeHelper.getInstance(LeDimApplication.getInstance(), params);
            mCdeHelper.setOnServiceConnectionListener(new OnServiceConnectionListener() {
                @Override
                public void onServiceConnected() {
                    // CDE已启动
                    LogInfo.log("jipengfei", "*****************CDE启动成功*****************");
                    mIsCdeReady = mCdeHelper.isReady();
                }

                @Override
                public void onServiceDisconnected() {
                    // bind启动的CdeService组件, client端与server端断开连接时回调
                    // 有可能是被系统杀死, 或者是CDE模块异常崩溃. 此后CDE服务不可用, 上层可根据需求调用cdeHelper.start进行重启.
                    LogInfo.log("jipengfei", "*****************cde断开连接*****************");

                }

            });
        }
        mCdeHelper.start();
        mIsCdeStarting = true;
    }

    /**
     * 停止cde服务
     */
    private void stopCde() {
        if (mCdeHelper != null) {
            mCdeHelper.stop();
        }
        mIsCdeStarting = false;
    }

    /**
     * 上传崩溃统计
     */
    public void staticsCrashInfo() {
        //if (null == mContext) {
        //    Log.e("LetvSDK", "statics crash info failed,context is null!");
        //    return;
        //}
        int crashCounts =
                PreferencesManager.getInstance(LeDimApplication.getInstance()).getCrashCount();
        if (crashCounts > 0) {
            LogInfo.LogStatistics("splash crash statistic:" + crashCounts);
            String cnt = "cnt=" + crashCounts;
            DataStatistics.getInstance()
                          .sendErrorInfo(LeDimApplication.getInstance(), "0", "0", LetvErrorCode.VIDEO_CRASH_ERROR, null, cnt, null, null, null, null);
            PreferencesManager.getInstance(LeDimApplication.getInstance()).setCrashCount(0);
        }
    }

    /**
     * 初始化LetvMediaPlayerManager（在主进程和pip进程都初始化）
     */
    private void initLetvMediaPlayerManager() {
        //if (null == mContext) {
        //    Log.e("LetvSDK", "init letv mediaplayer manager error,context is null!");
        //    return;
        //}
        LetvMediaPlayerManager.getInstance().setDebugMode(false);
        LetvMediaPlayerManager.getInstance().setLogMode(LetvConfig.isDebug());
        LetvMediaPlayerManager.getInstance()
                              .init(LeDimApplication.getInstance(), LetvConfig.getAppKey(), "hlXD", LetvConfig
                                      .getPcode(LeDimApplication.getInstance()
                                                                .getApplicationContext()), LetvTools
                                      .getClientVersionName(LeDimApplication.getInstance()));
    }

    /**
     * 初始化播放视频类型
     */
    public int setVType() {
        if (mDefaultHardStreamDecorder) {
            return mSupportLevel;
        }

        int sLevel = NativeInfos.getSupportLevel();
        if (sLevel == NativeInfos.SUPPORT_MP4_LEVEL || !NativeInfos.ifSupportVfpOrNeon()) {
            mDefaultHardStreamDecorder = false;
            // 请求mp4资源
            mVideoFormat = "no";
            mSupportLevel = NativeInfos.SUPPORT_MP4_LEVEL;
            mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
        }

        LogInfo.log("sguotao",
                "hard decode state:" + LetvMediaPlayerManager.getInstance().getHardDecodeState());
        LogInfo.log("sguotao", "最大主频：" + CpuInfosUtils.getMaxCpuFrequence());
        /**
         * harddecodestate
         * </br>
         * 0.不支持硬解
         * 1.支持硬解
         * 2.支持硬解，显示软硬解切换按钮
         * 3.支持硬解，不显示软硬解切换按钮
         */
        // 5.8如果不支持硬解，走原来逻辑
        if (LetvMediaPlayerManager.getInstance().getHardDecodeState() != 1) {
            LogInfo.log("zhuqiao", "不支持硬解");
            mDefaultHardStreamDecorder = false;
            sLevel = LetvMediaPlayerManager.getInstance().getSoftDecodeSupportLevel();
            if (sLevel == NativeInfos.SUPPORT_TS350K_LEVEL) {
                // 请求350k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS350K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
            } else if (sLevel == NativeInfos.SUPPORT_TS1000K_LEVEL) {
                // 请求800k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS1000K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
            } else if (sLevel == NativeInfos.SUPPORT_TS1300K_LEVEL) {
                // 请求1000k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS1300K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
            } else if (sLevel == NativeInfos.SUPPORT_TS180K_LEVEL) {
                // 请求350k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS180K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
            }
        } else {
            LogInfo.log("zhuqiao", "支持硬解");
            mDefaultHardStreamDecorder = true;
            sLevel = LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel();
            if (sLevel == NativeInfos.SUPPORT_TS350K_LEVEL) {
                // 请求350k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS350K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
            } else if (sLevel == NativeInfos.SUPPORT_TS1000K_LEVEL) {
                // 请求800k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS1000K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
            } else if (sLevel == NativeInfos.SUPPORT_TS1300K_LEVEL) {
                // 请求1000k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS1300K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
            } else if (sLevel == NativeInfos.SUPPORT_TS180K_LEVEL) {
                // 请求350k ts资源
                mVideoFormat = "ios";
                mSupportLevel = NativeInfos.SUPPORT_TS180K_LEVEL;
                mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
            }
        }
        LogInfo.log("sguotao",
                "---playNet--MainsetVType =" + mSupportLevel + " videoFormat =" + mVideoFormat +
                        ";;;defaultHardStreamDecorder---" + mDefaultHardStreamDecorder);
        return mSupportLevel;
    }

    // 当播放失败时重新设置VType，并且之后都走软解
    public void resetVType() {
        int sLevel = LetvMediaPlayerManager.getInstance().getSoftDecodeSupportLevel();
        if (sLevel == NativeInfos.SUPPORT_TS350K_LEVEL) {
            // 请求350k ts资源
            mVideoFormat = "ios";
            mSupportLevel = NativeInfos.SUPPORT_TS350K_LEVEL;
            mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
        } else if (sLevel == NativeInfos.SUPPORT_TS1000K_LEVEL) {
            // 请求800k ts资源
            mVideoFormat = "ios";
            mSupportLevel = NativeInfos.SUPPORT_TS1000K_LEVEL;
            mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
        } else if (sLevel == NativeInfos.SUPPORT_TS1300K_LEVEL) {
            // 请求1000k ts资源
            mVideoFormat = "ios";
            mSupportLevel = NativeInfos.SUPPORT_TS1300K_LEVEL;
            mDefaultLevel = PlayUtils.PLAY_LEVEL.HIGH;
        } else if (sLevel == NativeInfos.SUPPORT_TS180K_LEVEL) {
            // 请求180k ts资源
            mVideoFormat = "ios";
            mSupportLevel = NativeInfos.SUPPORT_TS180K_LEVEL;
            mDefaultLevel = PlayUtils.PLAY_LEVEL.LOW;
        }
        mDefaultHardStreamDecorder = false;
        LogInfo.log("zhuqiao",
                "---playNet--resetVType =" + mSupportLevel + " videoFormat =" + mVideoFormat +
                        ";;;defaultHardStreamDecorder---" + mDefaultHardStreamDecorder);
    }

    /**
     * 初始化广告
     */
    private void initAds() {
        //if (null == mContext) {
        //    Log.e("sguotao", "init ads failed,context is null!");
        //    return;
        //}
        // mContext = LeDimApplication.getInstance();
        LogInfo.log("sguotao", "ad: version:" +
                LetvUtils.getClientVersionName(LeDimApplication.getInstance()
                                                               .getApplicationContext()));
        // 初始化广告包
        AdsManager.getInstance()
                  .initAdData(LeDimApplication.getInstance()
                                              .getApplicationContext(), "androidPhone", "android", LetvUtils
                          .getClientVersionName(LeDimApplication.getInstance()
                                                                .getApplicationContext()), LetvConfig
                          .getPcode(LeDimApplication.getInstance()
                                                    .getApplicationContext()), LetvConfig.isDebug());
        AdsManager.getInstance()
                  .initAd(LeDimApplication.getInstance(), false, LetvConfig.isDebug(), mSupportLevel, LetvUtils
                          .generateDeviceId(LeDimApplication.getInstance()
                                                            .getApplicationContext()), JSBridgeUtil.getInstance());
        AdsManager.getInstance().setVipCallBack(new AdsManager.VipCallBack() {
            @Override
            public boolean isVip() {
                boolean isVip = PreferencesManager.getInstance(LeDimApplication.getInstance()
                                                                               .getApplicationContext())
                                                  .isVip();
                long cancelTime = PreferencesManager.getInstance(LeDimApplication.getInstance()
                                                                                 .getApplicationContext())
                                                    .getVipCancelTime();
                return isVip && (cancelTime > TimestampBean.getTm().getCurServerTime());
            }
        });

        /*广告控制开关*/
        AdsManager.getInstance().setShowAd(false);
    }

    /**
     * 初始化Flurry
     */
    private void initFlurry() {
        // 初始化flurry
        FlurryAgent.setLogEnabled(false);
        FlurryAgent.init(LeDimApplication.getInstance(), LetvConfig.getFlurryKey());
    }

    public String getVideoFormat() {
        LogInfo.log("sguotao", "playLibsVideoFormat:" + mVideoFormat);
        return mVideoFormat;
    }

    public boolean isCdeStarting() {
        return mIsCdeStarting;
    }

    public boolean isCdeReady() {return mIsCdeReady;}

    public void setIsInited(boolean isInited) {
        this.isInited = isInited;
    }

    /**
     * 广告推送开关
     **/
    public boolean isPush() {
        return true;
    }

    public void setPush(boolean isPush) {
    }

    public static int getPushType() {
        return 0;
    }

    public static void setPushType(int type) {
        //        pushType = type;
    }

    public int getDefaultLevel() {
        return mDefaultLevel;
    }

    /**
     * 广告拼接开关
     **/
    public static boolean getPinjie() {
        return true;
    }

    public boolean getDefaultHardStreamDecorder() {
        return mDefaultHardStreamDecorder;
    }

    public void setDefaultHardStreamDecorder(final boolean defaultHardStreamDecorder) {
        mDefaultHardStreamDecorder = defaultHardStreamDecorder;
    }

    public void setBritness(float bri) {
        PreferencesManager.getInstance(LeDimApplication.getInstance()).setBritness(bri);
    }

    public float getBritness() {
        return PreferencesManager.getInstance(LeDimApplication.getInstance()).getBritness();
    }

    public int getSuppportTssLevel() {
        return mSupportLevel;
    }

    /**
     * 离开应用时处理
     */
    public void onAppExit() {
        getInstance().stopCde();
        //        ImageDownloader.getInstance(instance).onDestory();
        AutoSwitchHandler.autoScrollObservable.clearAll();
        //        PreferencesManager.getInstance().setLocationState(false);
        //        sAppStartTime = 0;
        isInited = false;
    }

    /**
     * 调起LiteApp
     *
     * @param context
     * @param aid
     * @param vid
     * @param from
     */
    private void callLiteApp(Context context, long aid, long vid, int from) {
        Intent intent = new Intent();
        intent.setClassName("com.letv.android.client", "AlbumPlayActivity");
        intent.putExtra(PlayConstant.LAUNCH_MODE, from);
        intent.putExtra(PlayConstant.AID, (int) aid);
        intent.putExtra(PlayConstant.VID, (int) vid);
        intent.putExtra(PlayConstant.FROM, from);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    public IVideo getmVideo() {
        if (mVideo == null) {
            mVideo = new IVideo();
            mVideo.setVid(0);
        }
        return mVideo;
    }

}
